package org.example.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.Dto.CommunityDTO;
import org.example.Entity.Community;
import org.example.Entity.LearnHistory;
import org.example.Entity.LikeHistory;
import org.example.Entity.User;
import org.example.Mapper.CommunityMapper;
import org.example.Mapper.UserMapper;
import org.example.Service.CommunityService;
import org.example.Service.LikeHistoryService;
import org.example.Utils.HttpUtil;
import org.example.Utils.OSSUtil;
import org.example.Vo.CommunityVO;
import org.example.Vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community> implements CommunityService {

    @Resource
    private OSSUtil ossUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private LikeHistoryService likeHistoryService;

    @Resource
    private HttpUtil httpUtil;

    @Override
    public R publish(CommunityDTO communityDTO, String username) throws IOException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        StringBuilder fileUrls = new StringBuilder();
        if (communityDTO.getFiles() != null) {
            for (String fileUrl : communityDTO.getFiles()) {
                fileUrls.append(fileUrl);
            }
        }
        Community community = Community.builder()
                .content(communityDTO.getContent())
                .shareCount(0)
                .likeCount(0)
                .commentCount(0)
                .userId(user.getId())
                .fileUrl(fileUrls.toString())
                .type(communityDTO.getType())
                .createDate(Timestamp.valueOf(LocalDateTime.now()))
                .build();
        communityMapper.insert(community);
        return R.ok();
    }

    @Override
    public R flush(Integer type,String username) {
        LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Community::getType, type);
        List<Community> communities = communityMapper.selectList(wrapper);
        // 随机从中选择两个
        int size = communities.size();
        if (size > 2) {
            // 获取两个随机数
            int random1 = (int) (Math.random() * size);
            int random2 = (int) (Math.random() * size);
            while (random1 == random2) {
                random2 = (int) (Math.random() * size);
            }
            List<Community> list = new ArrayList<>();
            list.add(communities.get(random1));
            list.add(communities.get(random2));
            List<CommunityVO> resultList = new ArrayList<>();
            Integer userId = httpUtil.getUserId(username);
            for (Community community : list) {
                LambdaQueryWrapper<LikeHistory> likeWrapper = new LambdaQueryWrapper<>();
                likeWrapper.eq(LikeHistory::getCommunityId, community.getId());
                likeWrapper.eq(LikeHistory::getUserId, userId);
                Integer isLike = 0;
                if (likeHistoryService.getOne(likeWrapper) != null) {
                    isLike = 1;
                }else {
                    isLike = 0;
                }
                LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(User::getId, community.getUserId());
                User user = userMapper.selectOne(wrapper1);
                String fileUrl = community.getFileUrl();
                // 根据后缀名判断是图片还是视频
                Integer fileType = -1;
                if (fileUrl.endsWith(".jpg") || fileUrl.endsWith(".png") || fileUrl.endsWith(".jpeg")) {
                    fileType = 0;
                } else if (fileUrl.endsWith(".mp4")) {
                    fileType = 1;
                }
                CommunityVO communityVO = CommunityVO.builder()
                        .id(community.getId())
                        .content(community.getContent())
                        .fileUrl(fileUrl)
                        .avatarUrl(user.getAvatarUrl())
                        .username(user.getUsername())
                        .date(community.getCreateDate())
                        .likeCount(community.getLikeCount())
                        .shareCount(community.getShareCount())
                        .commentCount(community.getCommentCount())
                        .avatarUrl(user.getAvatarUrl())
                        .fileType(fileType)
                        .isLike(isLike)
                        .build();
                resultList.add(communityVO);
            }
            return R.ok(resultList);
        }
        return R.error("当前板块内容较少，请联系管理员");
    }

    @Override
    public R like(Integer id, String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        LambdaQueryWrapper<LikeHistory> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(LikeHistory::getUserId, user.getId()).eq(LikeHistory::getCommunityId, id);
        if (likeHistoryService.getOne(wrapper1) == null) {
            likeHistoryService.save(LikeHistory.builder().communityId(id).userId(user.getId()).build());
            LambdaQueryWrapper<Community> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(Community::getId, id);
            Community community = communityMapper.selectOne(wrapper2);
            community.setLikeCount(community.getLikeCount() + 1);
            communityMapper.updateById(community);
            return R.ok();
        }else {
            // 删除点赞记录
            likeHistoryService.remove(wrapper1);
            LambdaQueryWrapper<Community> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(Community::getId, id);
            Community community = communityMapper.selectOne(wrapper2);
            community.setLikeCount(community.getLikeCount() - 1);
            communityMapper.updateById(community);
            return R.error("已经点过赞了");
        }
    }

    @Override
    public R getCommunityById(Integer id,String username) {
        Integer userId = httpUtil.getUserId(username);
        LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Community::getId, id);
        Community community = communityMapper.selectOne(wrapper);
        if (community != null) {
            LambdaQueryWrapper<LikeHistory> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(LikeHistory::getUserId, userId).eq(LikeHistory::getCommunityId, id);
            int isLike = 0;
            if (likeHistoryService.getOne(wrapper1) != null) {
                isLike = 1;
            }
            CommunityVO communityVO = CommunityVO.builder()
                    .likeCount(community.getLikeCount())
                    .shareCount(community.getShareCount())
                    .commentCount(community.getCommentCount())
                    .isLike(isLike)
                    .build();
            return R.ok(communityVO);
        }else {
            return R.error("内容不存在");
        }
    }
}
